import { IPageResponse } from "../../types/CommonType";
import { ValidationError } from "../../utils/errors";
import { getTreeStructure } from "../../utils/tools";
import CodeGenerationModel from "../../dao/model/codeGeneration/CodeGenerationModel";
import CodeGenerationEntity, { ICodeGenerationModel } from "../../entities/codeGeneration/CodeGenerationEntity";
import { generCode } from "./index";

export class CodeGenerationService {
  /**
   * 添加数据
   */
  public static async add(admin: CodeGenerationEntity): Promise<true> {
    // 1. 转换类型
    admin = CodeGenerationEntity.transform(admin);
    // 2. 数据验证
    const errors = await admin.validateThis();
    if (errors.length > 0) {
      throw new ValidationError(errors[0]);
    }

    await CodeGenerationModel.create<ICodeGenerationModel>(admin);
    return true;
  }

  /**
   * 分页获取数据
   */
  public static async findByPage(offset: number, limit: number, where?: any): Promise<IPageResponse> {
    let data = await CodeGenerationModel.findAndCountAll<ICodeGenerationModel>({
      offset: limit * (offset - 1),
      limit,
      where,
    });

    const result: IPageResponse = {
      total: data.count,
      list: data.rows.map((item) => item.dataValues),
    };

    return result;
  }

  public static async findByList(where = {}) {
    return CodeGenerationModel.findAll<ICodeGenerationModel>({ where });
  }

  public static async findByTreeList(where: any = {}) {
    const result = await CodeGenerationModel.findAll<ICodeGenerationModel>({ where });

    return getTreeStructure<CodeGenerationEntity>(result.map((item) => item.dataValues));
  }

  /**
   * 通过id获取数据
   */
  public static async findById(id: string) {
    return CodeGenerationModel.findByPk<ICodeGenerationModel>(id);
  }

  /**
   * 修改数据
   */
  public static async update(data: any) {
    return CodeGenerationModel.update<ICodeGenerationModel>(data, {
      where: {
        id: data.id,
      },
    });
  }

  /**
   * 删除数据
   */
  public static async delete(id: string) {
    return CodeGenerationModel.destroy({
      where: {
        id,
      },
    });
  }

  public static async generateCode(id: string) {
    const data = await CodeGenerationModel.findByPk<ICodeGenerationModel>(id);
    if (data) {
      await generCode({
        name: data.dataValues.moduleName,
        fields: data.dataValues.fields.split(","),
        superDir: data.dataValues.superDir,
        tableName: data.dataValues.tableName,
      });
    }
    return true;
  }
}
